import json
import time
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from users import constants
from users.models import User


class CreateUserSerializer(serializers.ModelSerializer):
    """
    创建用户序列化器
    """
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label="JWT token", read_only=True)

    class Meta:
        model = User
        fields = ('id', 'nickname', 'password', 'sms_code', 'mobile', 'allow', 'token')
        extra_kwargs = {
            'nickname': {
                'min_length': 3,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许3-20个字符的用户名',
                    'max_length': '仅允许3-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 6,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许6-20个字符的密码',
                    'max_length': '仅允许6-20个字符的密码',
                }
            }
        }

    def validate_allow(self, value):
        """检验用户是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, data):
        # 判断短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = data['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data

    def create(self, validated_data):
        """
        创建用户
        """
        # 移除数据库模型类中不存在的属性
        del validated_data['sms_code']
        del validated_data['allow']
        validated_data['username'] = "CodeDragon_" + validated_data['mobile']
        validated_data['avatar_url'] = "img/yasuo.gif"
        validated_data['personal_url'] = '填写个人网站'
        user = super().create(validated_data)

        # 调用django的认证系统加密密码
        user.set_password(validated_data['password'])
        user.save()

        # 传递JWT Token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """

    class Meta:
        model = User
        fields = (
        'id', 'username', 'mobile', 'email', 'email_active', 'personal_url', 'nickname', 'avatar_url')


class UserPartInfoSerializer(serializers.ModelSerializer):
    """
    用户部分信息序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'nickname', 'avatar_url')


class UserUpdateUser(serializers.ModelSerializer):
    """
    更新用户数据序列化器
    """

    class Meta:
        model = User
        # 'nickname', 'mobile', 'email', 'personal_url', 'avatar_url', 'password'
        fields = ('nickname', 'mobile', 'email', 'personal_url', 'avatar_url', 'password', 'email_active')

    def update(self, instance, validated_data):
        instance.nickname = validated_data.get('nickname', instance.nickname)
        instance.mobile = validated_data.get('mobile', instance.mobile)
        if validated_data.get('email') is not None:
            if instance.email != validated_data.get('email'):
                instance.email_active = 0
        instance.email = validated_data.get('email', instance.email)
        instance.personal_url = validated_data.get('personal_url', instance.personal_url)
        instance.avatar_url = validated_data.get('avatar_url', instance.avatar_url)
        instance.set_password(validated_data.get('password', instance.password))
        instance.save()
        return instance


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    """
    添加用户浏览历史序列化器
    """

    history_title = serializers.CharField(label="历史记录标题")
    history_address = serializers.CharField(label="历史记录对应地址")
    create_time = serializers.CharField(label="历史记录时间", read_only=True)
    create_date = serializers.CharField(label="历史记录日期", read_only=True)

    def create(self, validated_data):
        """
        保存
        """
        user_id = self.context['request'].user.id
        history_title = validated_data['history_title']
        history_address = validated_data['history_address']
        now = time.localtime(time.time())
        create_time = time.strftime("%H:%M", now)
        create_date = time.strftime("%Y-%m-%d", now)

        data = {
            'history_title': history_title,
            'history_address': history_address,
            'create_time': create_time,
            'create_date': create_date
        }

        json_data = json.dumps(data)
        redis_conn = get_redis_connection("history")
        pl = redis_conn.pipeline()

        # 移除已经存在的本商品浏览记录
        # pl.lrem("history_%s" % user_id, 0, json_data)
        # 添加新的浏览记录

        pl.lpush("history_%s" % user_id, json_data)
        # 只保存最多5条记录
        pl.ltrim("history_%s" % user_id, 0, constants.USER_BROWSE_HISTORY_MAX_LIMIT - 1)

        pl.execute()

        return validated_data
